package com.zhuss.car.processor;

import com.zhuss.bean.bo.car.car.StartCarBo;
import com.zhuss.bean.vo.car.car.DetailCarVo;
import com.zhuss.car.db.dao.ext.CarDao;
import com.zhuss.car.db.entity.Car;
import com.zhuss.car.processor.cache.CarCache;
import com.zhuss.common.AbstractProcessor;
import com.zhuss.common.Processor;
import com.zhuss.db.entity.OpLog;
import com.zhuss.enums.LogActionEnum;
import com.zhuss.enums.MoudleEnum;
import com.zhuss.enums.StartStopEnum;
import com.zhuss.exception.DzcxException;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author summer
 * @date 2020/12/23 16:24
 */
@Component("carStart")
public class CarStart extends AbstractProcessor<Object, StartCarBo> implements Processor<Object, StartCarBo> {

    @Autowired
    private CarDao carDao;

    @Autowired
    @Qualifier("carRead")
    private CarRead carRead;

    @Autowired
    @Qualifier("carCache")
    private CarCache carCache;


    @Override
    public void check(StartCarBo startCarBo) throws DzcxException {
        DetailCarVo carVo = (DetailCarVo) carRead.detail(startCarBo.getCarId());
        if (StartStopEnum.启用.sameKey(carVo.getStatus())) {
            throw new DzcxException(ExceptionCode.当前数据不满足启用条件);
        }
    }

    @Override
    public Object process(StartCarBo param) throws DzcxException {
        Long carId = param.getCarId();

        Car record = new Car();
        record.setCarId(carId);
        record.setStatus(param.getStatus());

        record.setModifierId(param.getConcurrentUserId());
        record.setModifier(param.getConcurrentUserName());
        record.setModifyTime(new Date());
        carDao.updateByPrimaryKeySelective(record);

        String name = ((DetailCarVo) carRead.detail(carId)).getPlateNo();
        param.setName(name);

        carCache.clear(carId);
        return null;
    }

    @Override
    public Object log(StartCarBo param) throws DzcxException {
        OpLog record = new OpLog();
        record.setMoudle(MoudleEnum.车辆.key());
        record.setAction(LogActionEnum.车辆启用.key());
        record.setTargetId(param.getConcurrentUserId());
        record.setTargetName(param.getName());
        record.setContent("参数: " + JsonUtil.toJson(param));
        record.setReason(param.getExceptionReason());
        record.setCreatorId(param.getConcurrentUserId());
        record.setCreator(param.getConcurrentUserName());
        record.setCreateTime(new Date());
        log(record);
        return null;
    }
}
